package util;

import java.math.BigDecimal;

/**
 * 用于计算浮点数(float/double)的工具类
 * Created by butterfly on 2018/6/21.
 */
public class DoubleMath {
    //除法保留精度
    private static final int DEF_DIV_SCALE = 10;

    private DoubleMath() {
    }

    public static double add(double v1,double v2){
        BigDecimal f1 = BigDecimal.valueOf(v1);
        BigDecimal f2 = BigDecimal.valueOf(v2);
        return f1.add(f2).doubleValue();
    }
    public static double sub(double v1,double v2){
        BigDecimal f1 = BigDecimal.valueOf(v1);
        BigDecimal f2 = BigDecimal.valueOf(v2);
        return f1.subtract(f2).doubleValue();
    }
    public static double mul(double v1,double v2){
        BigDecimal f1 = BigDecimal.valueOf(v1);
        BigDecimal f2 = BigDecimal.valueOf(v2);
        return f1.multiply(f2).doubleValue();
    }
    public static double div(double v1,double v2){
        BigDecimal f1 = BigDecimal.valueOf(v1);
        BigDecimal f2 = BigDecimal.valueOf(v2);
        return f1.divide(f2,DEF_DIV_SCALE,BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public static void main(String[] args) {
        System.out.println(add(0.1,0.2));
        System.out.println(sub(0.1,0.2));
        System.out.println(mul(0.1,0.2));
        System.out.println(div(0.1,0.2));
    }
}
